<template>
  <div v-loading="loading" class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <label class="el-form-item-label">轮播图类型</label>
        <el-select v-model="query.type" style="width: 185px;" placeholder="请选择轮播图类型" class="filter-item" @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <label class="el-form-item-label">小区</label>
        <el-select v-model="query.xqId" style="width: 185px;" placeholder="请选择小区" class="filter-item" @keyup.enter.native="crud.toQuery">
          <el-option
            v-for="item in xqOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value">
          </el-option>
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="500px">
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="图片">
            <!-- 文件上传组件 -->
            <el-upload
              class="upload-demo"
              :limit="1"
              :action="fileUploadApi"
              :headers="headers"
              :on-preview="handlePreview"
              :before-upload="beforeUpload"
              :on-success="handleSuccess"
              :on-remove="removePic"
              :on-error="handleError"
              :file-list="fileList"
              list-type="picture-card"
            >
              <i class="el-icon-plus"></i>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500mb</div>
            </el-upload>
          </el-form-item>
          <el-form-item label="跳转地址" >
            <el-input v-model="form.jumpUrl" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="描述" prop="description">
            <el-input v-model="form.description" :rows="3" type="textarea" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="类型" prop="type">
            <el-select v-model="form.type" style="width: 160px" placeholder="请选择轮播图类型">
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column label="图片" width="80">
          <template slot-scope="{row}">
            <el-image
              :src="row.path"
              :preview-src-list="[row.path]"
              fit="contain"
              lazy
              class="el-avatar"
            >
              <div slot="error">
                <i class="el-icon-document" />
              </div>
            </el-image>
          </template>
        </el-table-column>
        <el-table-column prop="path" label="文件路径" />
        <el-table-column prop="jumpUrl" label="跳转地址" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="fileName" label="文件名" />
        <el-table-column prop="type" label="类型" >
          <template slot-scope="scope">
            <!-- 根据不同的值显示不同的内容 -->
            <span v-if="scope.row.type == 1">首页轮播图</span>
            <span v-else-if="scope.row.type == 2">食堂管理轮播图</span>
            <span v-else />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建日期" />
        <el-table-column v-if="checkPer(['admin','carouselManage:edit','carouselManage:del'])" label="操作" width="150px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
      <el-dialog :visible.sync="dialogPictrueVisible">
        <img width="100%" :src="dialogImageUrl" alt="">
      </el-dialog>
    </div>
  </div>
</template>

<script>
import crudCarouselManage from '@/api/system/carouselManage'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import { allList } from '@/api/system/regionManage'

const defaultForm = { id: null, createTime: null, updateTime: null, createBy: null, updateBy: null, deleted: null, storageId: null, path: null, jumpUrl: null, description: null, fileName: null, type: null, xqId: null }
export default {
  name: 'CarouselManage',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  cruds() {
    return CRUD({ title: '轮播图管理', url: 'api/carouselManage', idField: 'id', sort: 'id,desc', crudMethod: { ...crudCarouselManage }})
  },
  data() {
    return {
      permission: {
        add: ['admin', 'carouselManage:add'],
        edit: ['admin', 'carouselManage:edit'],
        del: ['admin', 'carouselManage:del']
      },
      rules: {
        description: [
          { required: true, message: '描述不能为空', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '轮播图类型', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'type', display_name: '轮播图类型' },
        { key: 'xqId', display_name: '小区id' }
      ],
      headers: { 'Authorization': getToken() },
      fileList: [],
      options: [{
        value: '1',
        label: '首页轮播图'
      }, {
        value: '2',
        label: '食堂管理轮播图'
      }],
      dialogImageUrl: '',
      loading: false,
      dialogPictrueVisible: false,
      xqOptions: []
    }
  },
  computed: {
    ...mapGetters([
      'baseApi',
      'fileUploadApi'
    ])
  },
  created() {
    allList().then(data => {
      if (data && data.data) {
        for (const item of data.data) {
          this.xqOptions.push({ 'value': item.id, 'label': item.communityName })
        }
      }
    })
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.optShow.download = false
      return true
    },
    // 编辑之前
    [CRUD.HOOK.beforeToEdit](obj, row) {
      this.fileList.push({ url: row.path })
      return true
    },
    // 取消添加之前
    [CRUD.HOOK.beforeAddCancel]() {
      this.fileList = []
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      this.crud.form.fileName = ''
      return true
    },
    // 取消编辑之前
    [CRUD.HOOK.beforeEditCancel]() {
      this.fileList = []
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      this.crud.form.fileName = ''
      return true
    },
    // 取消编辑之前
    [CRUD.HOOK.beforeSubmit]() {
      if (!this.crud.form.path || this.crud.form.path === '') {
        this.$message.error('请上传文件')
        return false
      }
      if (!this.crud.form.storageId || this.crud.form.storageId === '') {
        this.$message.error('请上传文件')
        return false
      }
      return true
    },
    // 提交保存之后
    [CRUD.HOOK.afterSubmit]() {
      this.fileList = []
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      this.crud.form.fileName = ''
      return true
    },
    // 删除图片
    removePic() {
      this.crud.form.path = ''
      this.crud.form.storageId = ''
      this.crud.form.fileName = ''
    },
    handleSuccess(res, file, fileList) {
      this.crud.form.path = res.path
      this.crud.form.storageId = res.id
      this.crud.form.fileName = res.realName
      this.crud.notify('上传成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
      this.dialogVisible = false
    },
    beforeUpload(file) {
      let isLt2M = true
      isLt2M = file.size / 1024 / 1024 < 5
      if (!isLt2M) {
        this.loading = false
        this.$message.error('上传文件大小不能超过 5mb!')
      }
      return isLt2M
    },
    handlePreview(file) {
      this.dialogImageUrl = file.url
      this.dialogPictrueVisible = true
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
      this.loading = false
    }
  }
}
</script>

<style scoped>

</style>
